<?php
namespace app\api\controller;

use think\facade\Cache;

use think\Controller;
use think\Request;
use app\api\model\Base;
use app\api\model\Member;
use app\api\model\MemberTmp;
use app\api\model\MemberAuth;
use app\api\model\Token;
use app\api\model\Auth;

class Common extends Controller
{
    protected $member = array();
    protected $isMember = 0;
    protected $sysconfig  = array(); //系统配置
    protected $allow = ['tourist', 'task']; //游客可访问的控制器
    
    public function initialize()
    {
        parent::initialize();
        $token = $this->request->param('token');
        $len = strlen($token);
        //token长度为30时为游客访问，32位时为正式会员
        if(!in_array($len, [30, 32])){
            die(apiError('token异常'));
        }
        $this->isMember = 1;
        $token_obj = new Token();
        $ret = $token_obj->_check($token);
        if(!$ret){
            die(apiError($token_obj->getError(), 202));
        }

        $token = $token_obj->_getMemberByToken($token);

        $mid = $token['mid'];
        $member_ob = new Member;
        $ret = $member_ob->_check($mid);

        if(!$ret){
            die(apiError($member_ob->getError()));
        }
        $member = $member_ob->_getInfoById($mid);

        $this->member = $member;
        $param = $this->request->request();

        $baseModel = new Base;
        $sys = $baseModel->getConfig();
        $this->sysconfig = $sys;
        $auth_obj = new Auth();
        $ret = $auth_obj->_checkSign($param, $member['id'], $sys['API_CYCLE']);
        if(!$ret){
            //die(apiError($auth_obj->getError()));
        }

    }
    

    
    /**
    * 校验api
    * @return bool
    */
    public function checkAuth(){
        $controller = $this->request->controller();
        $action = $this->request->action();
        
        $controller = strtolower($controller);
        $action = strtolower($action);
        
        $auth_model = new MemberAuth;
        $auth_data = $auth_model->field('id,controller,action')->where([['controller', '=', $controller], ['action', '=', $action]])->find();
        if(empty($auth_data)){
            return false;
        }
        
        return true;
    }
    
    
    /**
    * 校验api是否可调用
    */
    public function doCheckAuth($noCheckAction){

        $action = $this->request->action();
        foreach($noCheckAction as $k=>$v){
            $noCheckAction[$k] = strtolower($v);
        }
        if(empty($noCheckAction) || !in_array($action, $noCheckAction)){
            $isAuth = $this->checkAuth();
            if(!$isAuth){
                die(apiError('无权限'));
            }
        }
        
        return true;
    }
    
    
    /**
    * 校验游客可访问哪些接口
    */
    public function checkTmpApi(){
        
    }
}
